<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import {computed, PropType, reactive, ref, watch} from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { SysFileDetailVo } from '@/api/system/file/SysFile/types'
import { isBlank } from '@/utils/StringUtils'
import { useBaseWriteView } from '@/base/views/BaseWriteView'
import { sysDictChooseListApi } from '@/api/system/dict/SysDict'
import { KeyLabelValueVo } from '@/base/api/KeyLabelValueVo'
import { ElMessage, UploadUserFile, ElButton } from 'element-plus'
import { useUserStoreWithOut } from '@/store/modules/user'
// [[ OnflowGenerator Range (- selectFunctionImport -) Start ]]

// [[ OnflowGenerator Range (- selectFunctionImport -) End ]]

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<SysFileDetailVo>>,
    default: () => null
  },
  editType: {
    type: String,
    default: 'add'
  },
  editId: {
    type: Number,
    default: -1
  }
})
const isAdd = ref(props.editType === 'add')

const { formRegister, submit, doWatch } = useBaseWriteView(props)
doWatch()

const formRef = ref<typeof Form>()
// [[ OnflowGenerator Range (- dictFunctions -) Start ]]
const moduleNameOptions = ref<Array<KeyLabelValueVo>>([])
const getModuleName = async () => {
  const res = await sysDictChooseListApi('sysModuleName')
  moduleNameOptions.value = res.data
}
getModuleName()
const platformTypeOptions = ref<Array<KeyLabelValueVo>>([])
const getPlatformType = async () => {
  const res = await sysDictChooseListApi('platformType')
  platformTypeOptions.value = res.data
}
getPlatformType()
const sourceTypeOptions = ref<Array<KeyLabelValueVo>>([])
const getSourceType = async () => {
  const res = await sysDictChooseListApi('sysFileSourceType')
  sourceTypeOptions.value = res.data
}
getSourceType()
const fileGradeOptions = ref<Array<KeyLabelValueVo>>([])
const getFileGrade = async () => {
  const res = await sysDictChooseListApi('sysFileGrade')
  fileGradeOptions.value = res.data
}
getFileGrade()

// [[ OnflowGenerator Range (- dictFunctions -) End ]]

// [[ OnflowGenerator Range (- selectFunctions -) Start ]]

// [[ OnflowGenerator Range (- selectFunctions -) End ]]

const fileList = ref<UploadUserFile[]>([])
// 获取环境变量
const apiBasePath = import.meta.env.VITE_API_BASE_PATH
const minioPath = import.meta.env.VITE_FILE_SERVER_PATH

const fileGrade = ref('10')
const expireDate = ref<string>('')

// 禁用当前日期之前的所有日期
const disablePastDates = (date:Date) => {
  // 获取当前时间的零时零分零秒
  const today = new Date()
  today.setHours(0, 0, 0, 0)

  // 如果时间在今天之前，则禁用
  return date < today
}

const schema = reactive<FormSchema[]>([
  // [[ OnflowGenerator Range (- inputSchema -) Start ]]
  {
    field: 'fileName',
    label: '文件名',
    component: 'Input',
    componentProps: {
      placeholder: '请输入文件名',
      clearable: true,
      disabled: true
    },
    remove: isAdd.value
  },
  {
    field: 'originFileName',
    label: '原文件名',
    component: 'Input',
    componentProps: {
      placeholder: '请输入原文件名',
      clearable: true,
      disabled: true
    },
    remove: isAdd.value
  },
  {
    field: 'storePath',
    label: '文件存储路径',
    component: 'Input',
    componentProps: {
      placeholder: '请输入文件存储路径',
      clearable: true,
      disabled: true
    },
    remove: isAdd.value
  },
  {
    field: 'containerType',
    label: '容器类型',
    value: 'minio',
    component: 'Input',
    componentProps: {
      placeholder: '请输入容器类型',
      clearable: true,
      disabled: true
    },
    remove: isAdd.value
  },
  {
    field: 'moduleName',
    label: '所属模块',
    component: 'Select',
    componentProps: {
      placeholder: '请选择所属模块',
      clearable: true,
      filterable: true,
      options: moduleNameOptions
    }
  },
  {
    field: 'platformType',
    label: '平台类型',
    value: 'onflow-backend',
    component: 'Select',
    componentProps: {
      placeholder: '请选择平台类型',
      clearable: true,
      filterable: true,
      options: platformTypeOptions
    }
  },
  {
    field: 'md5',
    label: 'md5值',
    component: 'Input',
    componentProps: {
      placeholder: '请输入md5值',
      clearable: true,
      disabled: true
    },
    remove: isAdd.value
  },
  {
    field: 'fileSize',
    label: '文件大小',
    value: 0,
    component: 'InputNumber',
    componentProps: {
      placeholder: '请选择文件大小',
      clearable: true,
      disabled: true
    },
    remove: isAdd.value
  },
  {
    field: 'bucketName',
    label: '存储桶名称',
    component: 'Input',
    componentProps: {
      placeholder: '请输入存储桶名称',
      clearable: true,
      disabled: true
    },
    remove: isAdd.value
  },
  {
    field: 'sourceType',
    label: '文件来源',
    component: 'Select',
    componentProps: {
      placeholder: '请选择文件来源',
      clearable: true,
      filterable: true,
      options: sourceTypeOptions,
      disabled: true
    },
    remove: isAdd.value
  },
  {
    field: 'expireDate',
    label: '文件过期时间',
    component: 'DatePicker',
    value: expireDate.value,
    componentProps: {
      placeholder: '请选择文件过期时间',
      clearable: true,
      type: 'datetime',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      disabledDate: disablePastDates,
      onChange: (value) => {
        expireDate.value = value
      }
    }
  },
  {
    field: 'fileGrade',
    label: '文件等级',
    value: '10',
    component: 'Select',
    componentProps: {
      placeholder: '请选择文件等级',
      clearable: true,
      filterable: true,
      options: fileGradeOptions,
      onChange: (value: string) => {
        console.log('fileGrade.value', fileGrade.value)
        fileGrade.value = value
      }
    }
  },
  {
    field: 'filePath',
    label: '上传文件',
    component: 'Upload',
    componentProps: {
      action: apiBasePath + '/sysFile/upload.adw',
      showFileList: true,
      onSuccess: (_response, uploadFile) => {
        console.log('_response', _response)
        console.log('uploadFile', uploadFile)
        // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
        fileList.value[0] = {
          name: uploadFile.name,
          url: minioPath + '/' + _response.data.storePath
        }
        ElMessage.success('文件上传成功，请返回列表')
      },
      beforeUpload: (rawFile) => {
        if (rawFile.size / 1024 / 1024 > 200) {
          ElMessage.error('文件大小不能超过200MB')
          return false
        }
        return true
      },
      onRemove: () => {
        fileList.value = []
      },
      data: {
        moduleName: 'system',
        fileGrade: computed(() => fileGrade.value),
        expireDate: computed(() => expireDate.value)
      },
      headers: {
        Authorization: useUserStoreWithOut().getToken
      },
      limit: 1,
      multiple: false,
      slots: {
        default: () => (
          <>
            {fileList.value.length === 0 ? (
              <ElButton type="primary">上传文件</ElButton>
            ) : (
              <ElButton type="primary" disabled>
                移除文件后再上传
              </ElButton>
            )}
          </>
        ),
        tip: () => (
          <>
            <div class="el-upload__tip">文件不能超过200MB</div>
          </>
        )
      }
    },
    hidden: !isAdd.value
  },
// [[ OnflowGenerator Range (- inputSchema -) End ]]
  {
    field: 'createTime',
    label: '创建时间',
    component: 'Input',
    remove: isAdd.value,
    componentProps: {
      placeholder: '暂无创建时间',
      disabled: true
    }
  },
  {
    field: 'updateTime',
    label: '更新时间',
    component: 'Input',
    remove: isAdd.value,
    componentProps: {
      placeholder: '暂无更新时间',
      disabled: true
    }
  },
  {
    field: 'createUserName',
    label: '创建人',
    component: 'Input',
    remove: isAdd.value,
    componentProps: {
      placeholder: '暂无创建人',
      disabled: true
    }
  },
  {
    field: 'updateUserName',
    label: '更新人',
    component: 'Input',
    remove: isAdd.value,
    componentProps: {
      placeholder: '暂无更新人',
      disabled: true
    }
  }
])

const rules = reactive({
  // [[ OnflowGenerator Range (- rules -) Start ]]
  fileName: [
    required(),
    {
      validator: (_, value, callback) => {
        if (isBlank(value)) {
          callback()
          return
        }
        if (value.length > 300) {
          callback(new Error('文件名不能超过300个字符'))
        } else {
          callback()
        }
      }
    }
  ],
  originFileName: [
    required(),
    {
      validator: (_, value, callback) => {
        if (isBlank(value)) {
          callback()
          return
        }
        if (value.length > 300) {
          callback(new Error('原文件名不能超过300个字符'))
        } else {
          callback()
        }
      }
    }
  ],
  storePath: [
    required(),
    {
      validator: (_, value, callback) => {
        if (isBlank(value)) {
          callback()
          return
        }
        if (value.length > 500) {
          callback(new Error('文件存储路径不能超过500个字符'))
        } else {
          callback()
        }
      }
    }
  ],
  containerType: [
    required(),
    {
      validator: (_, value, callback) => {
        if (isBlank(value)) {
          callback()
          return
        }
        if (value.length > 64) {
          callback(new Error('容器类型不能超过64个字符'))
        } else {
          callback()
        }
      }
    }
  ],
  moduleName: [
    required(),
    {
      validator: (_, value, callback) => {
        if (isBlank(value)) {
          callback()
          return
        }
        if (value.length > 100) {
          callback(new Error('所属模块不能超过100个字符'))
        } else {
          callback()
        }
      }
    }
  ],
  platformType: [
    required(),
    {
      validator: (_, value, callback) => {
        if (isBlank(value)) {
          callback()
          return
        }
        if (value.length > 100) {
          callback(new Error('平台类型不能超过100个字符'))
        } else {
          callback()
        }
      }
    }
  ],
  md5: [
    {
      validator: (_, value, callback) => {
        if (isBlank(value)) {
          callback()
          return
        }
        if (value.length > 64) {
          callback(new Error('md5值不能超过64个字符'))
        } else {
          callback()
        }
      }
    }
  ],
  fileSize: [required()],
  bucketName: [
    {
      validator: (_, value, callback) => {
        if (isBlank(value)) {
          callback()
          return
        }
        if (value.length > 200) {
          callback(new Error('存储桶名称不能超过200个字符'))
        } else {
          callback()
        }
      }
    }
  ],
  sourceType: [required()],
  fileGrade: [required()]

// [[ OnflowGenerator Range (- rules -) End ]]
})

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="schema" ref="formRef" />
</template>
